package com.chezhujie.www.service;

import com.chezhujie.www.controller.admin.TuserController;
import com.chezhujie.www.domain.Trolepermission;
import com.chezhujie.www.domain.Tsuser;
import com.chezhujie.www.domain.Tuserrole;
import com.chezhujie.www.persistence.TuserMapper;
import com.chezhujie.www.persistence.TuserroleMapper;
import com.chezhujie.www.security.BadCredentialsException;
import com.chezhujie.www.security.UsernameNotFoundException;
import com.chezhujie.www.web.RequestUtils;
import com.xy.core.page.Pagination;
import com.xy.core.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Service("tuserService")
public class TuserService {
	@Autowired
	private TuserMapper tuserMapper;
	@Autowired
	private TuserroleMapper tuserroleMapper;
//	@Autowired
//	private PwdEncoder pwdEncoder;
	
	/**
	 * 查询用户的所有权限链接
	 * @param param
	 * @return
	 */
	public Set<Trolepermission> getTuserPer(Map<String,Object> param) {
		return tuserMapper.getTuserPer(param);
	}		
	
	/**
	 * 查询某个用户表通过用户名字
	 * @param param
	 * @return
	 */
	public Tsuser getTuserByName(Map<String,Object> param) {
		return tuserMapper.getTuserByName(param);
	}	
	
	
	/**
	 * 查询用户所有的名字
	 * @param param
	 * @return
	 */
	public List<String> getTuserALLName() {
		return tuserMapper.getTuserALLName();
	}	
	
	
	/**
	 * 查询某个用户表
	 * @param param
	 * @return
	 */
	public Tsuser getTuser(Map<String,Object> param) {
		return tuserMapper.getTuser(param);
	}
   
	/**
	 * 查询用户表列表
	 * @return
	 */
	public Map<String,Object> getTuserList(Map<String,Object> param) {
		Map<String,Object> returnMap = new HashMap<String,Object>();
		returnMap.put("total", tuserMapper.getTotalRows(param));
		returnMap.put("rows", tuserMapper.getTuserList(param));
		return returnMap;
	}
   
	/**
	 * 查询用户表列表
	 * @return
	 */
	public Pagination getTuserList(Map<String,Object> param, int pageSize, Integer pageNo, String order, String sort) {
		Pagination p = new Pagination();
		p.setPageNo(pageNo);
		p.setPageSize(pageSize);
		p.setOrder(order);
		p.setSort(sort);
		param.putAll(p.toMap());
		int count=tuserMapper.getTotalRows(param);
		List<Tsuser> list=	tuserMapper.getTuserList(param);
	
		p.setList(list);
		p.setTotalCount(count);
		return p;
		
	}
      
	/**
	 * 新增用户表
	 * @param tuser
	 * @param param
	 */
	@Transactional
	public void insertTuser(Tsuser tuser) {
		tuser.setUserid(UUIDUtils.getUUID());
//		tuser.setPasswd(pwdEncoder.encodePassword(tuser.getPasswd()));
		tuser.setPasswd(tuser.getPasswd());
		tuserMapper.insertTuser(tuser);
	}
   
	/**
	 * 编辑用户表
	 * @param tuser
	 * @param param
	 */
	@Transactional
	public void updateTuser(Tsuser tuser) {
		if(null!=tuser.getPasswd() && !"".equals(tuser.getPasswd())){
			
//			tuser.setPasswd(pwdEncoder.encodePassword(tuser.getPasswd()));
			tuser.setPasswd(tuser.getPasswd());
		}
		else
			tuser.setPasswd(null);
		tuserMapper.updateTuser(tuser);
	}
   
	/**
	 * 删除用户表
	 * @param param
	 */    
	@Transactional
	public void deleteTuser(List<String> useridList) {
		for(String userid: useridList){
	  		Map<String,Object> param = new HashMap<String,Object>();
	  		param.put("userid", userid);
	 	   tuserMapper.deleteTuser(param);	  		
		}
	}
	public Tsuser login(HttpServletRequest request, String username, String password)
			throws UsernameNotFoundException, BadCredentialsException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("username", username);

		List<Tsuser> l = tuserMapper.getTuserList(map);

		if (l.size() == 0||"-1".equals(l.get(0).getStatus())) {
			throw new UsernameNotFoundException("username not found: "
					+ username);
		}
		Tsuser user = l.get(0);

		String ip = RequestUtils.getIpAddr(request);
//		if (!pwdEncoder.isPasswordValid(adminuser.getPasswd(), password)) {
//			updateLoginError(adminuser, ip);
//			throw new BadCredentialsException("password invalid");
//		}
		map.clear();
		map.put("userid", user.getUserid());
		List<Tuserrole> l1=	tuserroleMapper.getTuserroleList(map);
		Set s=new HashSet();
		for(Tuserrole t:l1){
			s.add(t.getRoleid());
		}
		user.setTroles(s);
		
//		if(adminuser.)
	/*	if (!adminuser.getActivation()) {
			throw new BadCredentialsException("account not activated");
		}*/
		updateLoginSuccess(user, ip);
		request.getSession().setAttribute(TuserController.AUTH_KEY, user);
		return user;
	}
	public void updateLoginSuccess(Tsuser user,String ip) {/*
		UnifiedUser adminuser = findById(userId);
		Date now = new Timestamp(System.currentTimeMillis());

		adminuser.setLoginCount(adminuser.getLoginCount() + 1);
		adminuser.setLastLoginIp(ip);
		adminuser.setLastLoginTime(now);

		adminuser.setErrorCount(0);
		adminuser.setErrorTime(null);
		adminuser.setErrorIp(null);
	*/}

	public void updateLoginError(Tsuser user,String ip) {/*
		UnifiedUser adminuser = findById(userId);
		Date now = new Timestamp(System.currentTimeMillis());
		ConfigLogin configLogin = configMng.getConfigLogin();
		int errorInterval = configLogin.getErrorInterval();
		Date errorTime = adminuser.getErrorTime();

		adminuser.setErrorIp(ip);
		if (errorTime == null
				|| errorTime.getTime() + errorInterval * 60 * 1000 < now
						.getTime()) {
			adminuser.setErrorTime(now);
			adminuser.setErrorCount(1);
		} else {
			adminuser.setErrorCount(adminuser.getErrorCount() + 1);
		}
	*/}

	public boolean getTuserByName(String username) {
		Map<String, Object> map=new HashMap<String, Object>();
			map.put("username", username);
		List<Tsuser> list=	tuserMapper.getTuserList(map);
		if(list!=null && list.size()>0){
			return true;
		}else{
			
			return false;
		}
	}
}